package kinon.canteen.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.io.Serializable;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import kinon.canteen.R;
import kinon.canteen.activity.MessageActivity;
import kinon.canteen.activity.OrderFoodActivity;
import kinon.canteen.activity.TipsActivity;
import kinon.canteen.activity.TipsContextActivity;
import kinon.canteen.activity.WebActivity;
import kinon.canteen.adapter.HomeIcomAdapter;
import kinon.canteen.adapter.HomeRecomAdapter;
import kinon.canteen.application.Constant;
import kinon.canteen.bean.HomeBean;
import kinon.canteen.bean.HomeMsgBean;
import kinon.canteen.bean.base.BaseBean;
import kinon.canteen.fragment.BaseFragment;
import kinon.canteen.network.HttpManage;
import kinon.canteen.network.http.CommonSubscriber;
import kinon.canteen.util.HomeManage.HomeManage;
import kinon.canteen.util.RxBus;
import kinon.canteen.util.RxUtil;
import kinon.canteen.util.ShardPManager;
import kinon.canteen.util.SysTimeManage;
import kinon.canteen.util.glide.GlideImageLoader;
import kinon.canteen.util.glide.GlideUtils;
import kinon.canteen.view.MyGridView;

/**
 * Created by luohao on 2017-07-05.
 */

public class HomeFragment extends BaseFragment implements
        View.OnClickListener {

    private View mView;
    private RelativeLayout rl_topbar;
    private TextView tv_topMsg;
    private SmartRefreshLayout smart_home;
    private Banner banner_home;
    private MyGridView gv_homeIcom;
    private LinearLayout ll_homeMsg;
    private LinearLayout ll_homeRecom;
//    private ListView lv_homeMsg;
    private MyGridView gv_homeRecom;
//    private ListView lv_tip;
    private ImageView img_tip;
    private TextView tv_tipTitle;
    private TextView tv_tipContent;
    private RelativeLayout rl_tip;
    private RelativeLayout rl_moreTip;
    //消息
    private RelativeLayout rl_book;
    private RelativeLayout rl_homemsg;
    private TextView tv_bookData;
    private TextView tv_bookContent;
    private TextView tv_msgData;
    private TextView tv_msgContent;

    private HomeBean mHomeBean=null;
    HomeIcomAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_home_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        rl_topbar= (RelativeLayout) mView.findViewById(R.id.rl_topbar);
        tv_topMsg= (TextView) mView.findViewById(R.id.tv_topMsg);
        smart_home= (SmartRefreshLayout) mView.findViewById(R.id.smart_home);
        banner_home= (Banner) mView.findViewById(R.id.banner_home);
        gv_homeIcom= (MyGridView) mView.findViewById(R.id.gv_homeIcom);
        ll_homeMsg= (LinearLayout) mView.findViewById(R.id.ll_homeMsg);
        ll_homeRecom= (LinearLayout) mView.findViewById(R.id.ll_homeRecom);
//        lv_homeMsg= (ListView) mView.findViewById(R.id.lv_homeMsg);
        gv_homeRecom= (MyGridView) mView.findViewById(R.id.gv_homeRecom);
        img_tip= (ImageView) mView.findViewById(R.id.img_tip);
        tv_tipTitle= (TextView) mView.findViewById(R.id.tv_tipTitle);
        tv_tipContent= (TextView) mView.findViewById(R.id.tv_tipContent);
        rl_tip= (RelativeLayout) mView.findViewById(R.id.rl_tip);
        rl_moreTip= (RelativeLayout) mView.findViewById(R.id.rl_moreTip);
        tv_bookData= (TextView) mView.findViewById(R.id.tv_bookData);
        tv_bookContent= (TextView) mView.findViewById(R.id.tv_bookContent);
        tv_msgData= (TextView) mView.findViewById(R.id.tv_msgData);
        tv_msgContent= (TextView) mView.findViewById(R.id.tv_msgContent);
        rl_book= (RelativeLayout) mView.findViewById(R.id.rl_book);
        rl_homemsg= (RelativeLayout) mView.findViewById(R.id.rl_homemsg);
        rl_topbar.setBackgroundResource(R.color.white_00f);
        tv_topMsg.setVisibility(View.VISIBLE);
        getHome();
        addListener();
    }
    private void addListener(){

        tv_topMsg.setOnClickListener(this);
        rl_tip.setOnClickListener(this);
        rl_moreTip.setOnClickListener(this);
        ll_homeRecom.setOnClickListener(this);
        rl_homemsg.setOnClickListener(this);
        rl_book.setOnClickListener(this);
        gv_homeIcom.setOnItemClickListener(itemListener);
        gv_homeRecom.setOnItemClickListener(itemListener);

    }
    private void showBanner(){
        ArrayList<String> images=new ArrayList<>();
        for(HomeBean.Pictures ad:mHomeBean.getPictures()){
            images.add(ad.getPic());
        }
        //设置banner样式
        banner_home.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner_home.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner_home.setImages(images);
        //设置banner动画效果
        banner_home.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当banner样式有显示title时）
//        banner_home.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner_home.isAutoPlay(true);
        //设置轮播时间
        banner_home.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
//        banner_home.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner_home.start();
    }


    private void getHome(){
        Disposable disposable= HttpManage.getInstance()
                .getHomeInfo(ShardPManager.getInstance().getToken())
                .compose(RxUtil.<BaseBean<HomeBean>>rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<BaseBean<HomeBean>>() {
                    @Override
                    public void onNext(BaseBean<HomeBean> homeBean) {
                        getHomeMsg();
                        mHomeBean=homeBean.getData();
                        showView();
                    }
                    @Override
                    public void onFail(Throwable t, int code, String msg) {
                    }
                });
    }

    private void getHomeMsg(){
        Disposable disposableMsg=HttpManage.getInstance()
                .getHomeMsg(ShardPManager.getInstance().getToken())
                .compose(RxUtil.<BaseBean<HomeMsgBean>>rxSchedulerHelper())
                .compose(RxUtil.<HomeMsgBean>handleResult())
                .subscribeWith(new CommonSubscriber<HomeMsgBean>(false){
                    @Override
                    public void onNext(HomeMsgBean s) {
                        tv_bookData.setText(SysTimeManage.getInstage()
                                .getYMD(System.currentTimeMillis()));
                        tv_bookContent.setText(s.getNote());
                        tv_msgData.setText(s.getMessage().getTime());
//                        tv_msgContent.setText(s.getMessage().getContent());
                        tv_msgContent.setText(Html.fromHtml(s.getMessage().getContent()));
                    }

                    @Override
                    public void onFail(Throwable t, int code, String msg) {
                        ll_homeMsg.setVisibility(View.GONE);
                    }
                });
    }

    private void showView(){
        HomeManage.getInstance().setHomeBean(mHomeBean);
        showBanner();
         adapter=new HomeIcomAdapter(mHomeBean
                .getHome(),getActivity());
        gv_homeIcom.setAdapter(adapter);


        if(mHomeBean.getProducts()!=null &&
                mHomeBean.getProducts().size()>0 ){
            ll_homeRecom.setVisibility(View.VISIBLE);
            HomeRecomAdapter recomAdapter=new HomeRecomAdapter
                    (mHomeBean.getProducts(),getActivity());
            gv_homeRecom.setAdapter(recomAdapter);
        }

        GlideUtils.getInstance().displayImage(getActivity(),
                mHomeBean.getArticle().getPic(),img_tip);
        tv_tipTitle.setText(mHomeBean.getArticle().getTitle());
        tv_tipContent.setText(mHomeBean.getArticle().getBrief());



    }

    private AdapterView.OnItemClickListener itemListener=new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            switch (adapterView.getId()){
                case R.id.gv_homeIcom:

                    if(mHomeBean.getHome().get(i).getName().equals("shop") /*||
                            mHomeBean.getHome().get(i).getId()==11*/){
                        intentFoodActivity(1);

                    }else if(mHomeBean.getHome().get(i).getName().equals("buy_food")
                            /*||mHomeBean.getHome().get(i).getId()==3*/){
                        intentFoodActivity(0);
                    }else{
                        Intent intent=new Intent(getActivity(), WebActivity.class);
                        String url=mHomeBean.getHome().get(i).getUrl();
                        intent.putExtra("url",mHomeBean.getHome().get(i).getUrl());
                        intent.putExtra("title",mHomeBean.getHome().get(i).getTitle());
                        startActivityForResult(intent,Constant.HOME_FRAGMENT);
                        Log.e("lh", "getUrl== "+url);
                    }
                    break;
                case R.id.gv_homeRecom:
                    intentFoodActivity(0);
                    break;
            }
        }
    };

    private void intentFoodActivity(int type){
        Intent food=new Intent(getActivity(),
                OrderFoodActivity.class);
        food.putExtra("goodType",type);
        startActivityForResult(food,Constant.HOME_FRAGMENT);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_tip:
                Intent intetn=new Intent(getActivity(),
                        TipsContextActivity.class);
                intetn.putExtra("tipcontent",
                        (Serializable) mHomeBean.getArticle());
                startActivity(intetn);
            break;
            case R.id.rl_moreTip:
                Intent moreTip=new Intent(getActivity(),
                        TipsActivity.class);
                startActivity(moreTip);
            break;
            case R.id.ll_homeRecom:
            case R.id.gv_homeRecom:
                Intent food=new Intent(getActivity(),
                        OrderFoodActivity.class);
                startActivity(food);
            break;
            case R.id.tv_topMsg:
            case R.id.rl_homemsg:
                Intent msgIntent=new Intent(getActivity(),
                        MessageActivity.class);
                startActivity(msgIntent);
            break;
            case R.id.rl_book:
                int position = 0;
                for(int i=0;i<mHomeBean.getHome().size();i++){
                    if(mHomeBean.getHome().get(i).getId()==17){
                        position=i;
                        break;
                    }
                }
                Intent intent=new Intent(getActivity(), WebActivity.class);
                String url=mHomeBean.getHome().get(position).getUrl();
                intent.putExtra("url",url);
                intent.putExtra("title",mHomeBean.getHome().get(position).getTitle());
                startActivityForResult(intent,Constant.HOME_FRAGMENT);
            break;
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        banner_home.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner_home.stopAutoPlay();
    }
}
